package com.villaday.idf.fragment;


import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.os.Bundle;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.R;
import com.villaday.idf.activity.MyOrderDetailActivity;
import com.villaday.idf.activity.OrderDetailsActivity;
import com.villaday.idf.adapter.OrderAdapter;
import com.villaday.idf.base.AbsRecyclerViewAdapter;
import com.villaday.idf.base.BaseDialog;
import com.villaday.idf.base.BaseFragment;
import com.villaday.idf.base.OnAdapterCallbackListener;
import com.villaday.idf.custom.ConfirmDialog;
import com.villaday.idf.custom.DividerGridItem;
import com.villaday.idf.custom.GridDividerItemDecoration;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.custom.SlideRecyclerView;
import com.villaday.idf.model.GatewayOrders;
import com.villaday.idf.model.gatewayOrdersEntity;
import com.villaday.idf.model.ordersEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.Unbinder;
import me.bakumon.statuslayoutmanager.library.OnStatusChildClickListener;
import me.bakumon.statuslayoutmanager.library.StatusLayoutManager;

import static android.content.Context.CLIPBOARD_SERVICE;

/**
 * 我的订单
 */
public class MyOrderFragment extends BaseFragment implements OkHttpUtil.OnDataListener, OnAdapterCallbackListener, View.OnClickListener, AbsRecyclerViewAdapter.OnItemClickListener, AbsRecyclerViewAdapter.OnBtnListener, SwipeRefreshLayout.OnRefreshListener {


    Unbinder unbinder;
    private int pageNo = 1;
    private int nextIndex = 1;
    private int pageSize = 10;
    private Gson gson = new GsonBuilder().create();

    private LoadingDialog loadingDialog;
    @BindView(R.id.rv)
//    RecyclerView rv;
            SlideRecyclerView rv;
    @BindView(R.id.srl)
    SwipeRefreshLayout srl;
    List<ordersEntity.BodyEntity.ListEntity> data = new ArrayList();
    private OrderAdapter orderAdapter;
    private StatusLayoutManager statusLayoutManager;

    public MyOrderFragment() {
        // Required empty public constructor
    }

    public static MyOrderFragment instance(int type) {
        MyOrderFragment myOrderFragment = new MyOrderFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        myOrderFragment.setArguments(bundle);
        return myOrderFragment;
    }

    @Override
    protected int getViewResId() {
        return R.layout.fragment_my_order;
    }


    /* @OnClick(R.id.tv_into_order)
     public void onViewClicked() {
         Intent intent = new Intent(getContext(), MyOrderDetailActivity.class);
         startActivity(intent);

     }*/
    @Override
    protected void init(View v) {

        statusLayoutManager = setupDefaultStatusLayoutManager(srl, new OnStatusChildClickListener() {
            @Override
            public void onEmptyChildClick(View view) {

            }

            @Override
            public void onErrorChildClick(View view) {
                loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getActivity().getFragmentManager(), "loading");

                loadData();
            }

            @Override
            public void onCustomerChildClick(View view) {

            }
        });
        srl.setOnRefreshListener(this);
        loadingDialog = LoadingDialog.newInstance("加载中");
        loadingDialog.show(getActivity().getFragmentManager(), "loading");
        rv.setLayoutManager(new LinearLayoutManager(getContext()));
        orderAdapter = new OrderAdapter(getContext(), this, this,rv);
        rv.setAdapter(orderAdapter);
        rv.addItemDecoration(new DividerGridItem(getContext(),GridDividerItemDecoration.ATTRS_W));
        orderAdapter.setOnItemClickListener(this);
        orderAdapter.setOnBtnListener(this);
       /* View inflate = View.inflate(getContext(), R.layout.recycle_head, null);
        homeListSaleAdapter.addHeaderView(inflate);*/
        orderAdapter.setEmptyView2(R.layout.empty_order_tips, true, R.id.tv_perchase);
        orderAdapter.setEmptyTips(R.id.tv_emptyTips, "您还没有相关订单");

/*        orderAdapter.setOnSwipeItemDelClickListener(new OnSwipeItemDelClickListener() {
            @Override
            public void delItem(int position) {
//                Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
//                itemAdapter.removeItemByPosition(position);
            }
        });

        orderAdapter*/


        //initHead(inflate);
        //添加删除线
        //tvDelete.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
    }

    @Override
    protected void loadData() {
        getData();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNo", pageNo + "");
        map.put("pageSize", pageSize + "");
        int type = (int) getArguments().get("type");
        switch (type) {
            case 0: {//"全部"
                map.put("status", "-1");

            }
            break;
            case 1: {// "待支付"
                map.put("status", "wait_pay");

            }
            break;
            case 2: {//"待使用",
                map.put("status", "wait_use");

            }
            break;
            case 3: {// "已完成"
                map.put("status", "completed");

            }
            break;
            case 4: {// "取消/退款"
                map.put("status", "cancel_refund");

            }
            break;
        }


        OkHttpUtil.getJSON(getContext(), Constant.URL.orders, map, this);
    }


    //复制方法
    private void initCopy() {

        ClipboardManager mClipboardManager = mClipboardManager =
                (ClipboardManager) getActivity().getSystemService(CLIPBOARD_SERVICE);
        ClipData mClipData;
        String text = "hello world";
        mClipData = ClipData.newPlainText("test", text);
        mClipboardManager.setPrimaryClip(mClipData);

       /* ClipData clipData = mClipboardManager.getPrimaryClip();
        ClipData.Item item = clipData.getItemAt(0);
        String text = item.getText().toString();*/
    }


    @Override
    public void onResponse(String url, String json) {
        if (statusLayoutManager != null) {
            statusLayoutManager.showSuccessLayout();
        }
        dismissLoading();
        if (!TextUtils.isEmpty(json)) {
            if (Constant.URL.orders.equals(url)) {
                LogeUtil.e("orders", getArguments().get("type") + "------" + json);
                ordersEntity ordersEntitys = gson.fromJson(json, ordersEntity.class);
                removeLoadingItem();
                if ("200".equals(ordersEntitys.getCode())) {
                    if (pageNo == 1 && ordersEntitys.getBody().getList() != null && ordersEntitys.getBody() != null) {
                        data.clear();
                    }
                    data.addAll(ordersEntitys.getBody().getList());
                    if (ordersEntitys.getBody().isHasNext()) {
                        data.add(new ordersEntity.BodyEntity.ListEntity(1));
                        nextIndex = pageNo + 1;
                    } else {
                        addBaseLine();
                    }

                } else {
                    addBaseLine();
                }
                orderAdapter.setData(data);
            }
        }
    }

    @Override
    public void onFailure(String url, String error) {
        dismissLoading();
        if (statusLayoutManager != null) {
            statusLayoutManager.showErrorLayout();
        }
        ToastUtil.initToast(getContext(),"网络错误");
    }

    @Override
    public void onCallback() {
        if (nextIndex == pageNo + 1) {
            pageNo++;
            getData();
        }

    }

    @Override
    public void onClick(View view) {

    }

    @Override
    public void onItemClick(View v, final int position) {
        switch (v.getId()) {
            case R.id.tv_other_operation://查看发票
                break;
            case R.id.tv_into_order:
            case R.id.ll_goods_layout:
                if (data.get(position).getType()==15){//酒店
                    Intent intent = new Intent(getActivity(), OrderDetailsActivity.class);
                    intent.putExtra("orderNo", data.get(position).getOrderNo());
                    startActivityForResult(intent, Constant.Code.OrderNo);

                }else {
                    Intent intent = new Intent(getActivity(), MyOrderDetailActivity.class);
                    intent.putExtra("orderNo", data.get(position).getOrderNo());
                    startActivityForResult(intent, Constant.Code.OrderNo);
                }


                break;

            case R.id.tv_del: {
                ConfirmDialog confirmDialog = ConfirmDialog.newInstance("确定要删除该订单吗?", "取消", "确定");
                confirmDialog.setOnItemClickListener(new BaseDialog.OnItemClickListener() {
                    @Override
                    public void onItemClick(View v) {

                        switch (v.getId()) {
                            case R.id.btn_confirmDialog: {
                                loadingDialog = LoadingDialog.newInstance("请求中...");
                                loadingDialog.show(getActivity().getFragmentManager());
                                Map<String, Object> map = new HashMap<>();
                                OkHttpUtil.postJson(getActivity(), Constant.URL.gateway_orders, new GatewayOrders(2, data.get(position).getOrderNo()), map, new OkHttpUtil.OnDataListener() {
                                    @Override
                                    public void onResponse(String url, String json) {
                                        dismissLoading();
                                        LogeUtil.e("gateway_orders", json);
                                        gatewayOrdersEntity goe = gson.fromJson(json, gatewayOrdersEntity.class);
                                        if ("200".equals(goe.getCode())) {
                                            //重新排列数据
                                            onRefresh();
                                            rv.closeMenu();
                                        }
                                    }

                                    @Override
                                    public void onFailure(String url, String error) {

                                    }
                                });
                            }
                            break;
                        }

                    }
                });
                confirmDialog.show(getActivity().getFragmentManager());
            }
            break;
        }
    }

    private void removeLoadingItem() {
        if (data.size() > 0) {
            if (data.get(data.size() - 1).getMyType() == 1) {
                data.remove(data.size() - 1);
            }
        }
    }

    private void addBaseLine() {
        if (pageNo != 1) {
            data.add(new ordersEntity.BodyEntity.ListEntity(2));
        }
    }

    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        if (srl != null && srl.isRefreshing()) {
            srl.setRefreshing(false);
        }

    }

    //空数据跳转
    @Override
    public void function() {
        getActivity().setResult(Activity.RESULT_OK);
        getActivity().finish();
    }

    @Override
    public void onRefresh() {
        pageNo = 1;
        nextIndex = 1;
        getData();
    }

    @Override
    public void onResume() {
        super.onResume();
        onRefresh();
    }
}
